package se.teamscape.client.presenter;

import java.util.ArrayList;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.place.PlaceRequestEvent;
import se.teamscape.client.place.EditPersonPlace;
import se.teamscape.client.rpc.CachingDispatchAsync;
import se.teamscape.client.rpc.DispatchCallback;
import se.teamscape.client.utils.NameValuePair;
import se.teamscape.shared.model.Person;
import se.teamscape.shared.rpc.GetModel;
import se.teamscape.shared.rpc.GetModelResult;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;

/**
 * Presenter that works with presenting Person data.
 * 
 * @author Andreas Borglin
 * 
 */
public class ShowPersonPresenter extends ShowDataPresenter {

    private String mPersonId;
    private final CachingDispatchAsync mDispatcher;

    @Inject
    public ShowPersonPresenter(Display display, EventBus eventBus, CachingDispatchAsync dispatcher) {
        super(display, eventBus);
        this.mDispatcher = dispatcher;
    }

    @Override
    protected void onLazyBind() {

        display.getEdit().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                PlaceRequest res = new PlaceRequest(EditPersonPlace.NAME).with(EditPersonPlace.PARAM_ID, mPersonId);
                eventBus.fireEvent(new PlaceRequestEvent(res));
            }
        });

    }

    private void updateData(final String id) {

        mPersonId = id;

        mDispatcher.executeWithCache(new GetModel(id, Person.class.getName()), new DispatchCallback<GetModelResult>() {

            @Override
            public void callback(GetModelResult result) {
                Person person = (Person) result.getModel();
                if (person == null)
                    Window.alert("no person with id = " + id);
                ArrayList<NameValuePair<String>> list = Person.getAsList(person);
                display.setData(list);
                viewUpdated();
            }

        });

    }

    @Override
    protected void onRevealDisplay() {

        if (needsUpdate()) {
            updateData(getId());
        }

    }
}
